<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重建二叉树</title>
</head>
<body>
    <script>

        var qianxu = [1, 2, 4, 8, 9, 5, 10, 11, 3, 6, 12, 7] //根左右
        var zhonxu = [8, 4, 9, 2, 10, 5, 11, 1, 12, 6, 3, 7] //左根右
        function treeNode(value){
            this.node = value;
            this.left = null;
            this.right = null;
        }

        function buildtree(qianxu,zhonxu){
            if(qianxu[0]){
                var res = new treeNode(qianxu[0])
                var root = qianxu[0];
                var index = zhonxu.indexOf(root);

                var qianxuLeft  = qianxu.slice(1,index +1);
                var zhonxuLeft  = zhonxu.slice(0,index)
                let leftTree = buildtree(qianxuLeft,zhonxuLeft)

                var qianxuRight = qianxu.slice(index+1);
                var zhonxuRight = zhonxu.slice(index+1)
                let rightTree = buildtree(qianxuRight,zhonxuRight)

                res = new treeNode(root)
                res.left  = leftTree;
                res.right = rightTree;
                return res;
            }
        }
        console.log(buildtree(qianxu,zhonxu))
    </script>
</body>
</html>